package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.WorkExperience;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.WorkExperienceRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class WorkExperienceService {

    private final WorkExperienceRepository workExperienceRepository;
    private final ApplicationRepository applicationRepository;

    public WorkExperienceService(WorkExperienceRepository workExperienceRepository, ApplicationRepository applicationRepository) {
        this.workExperienceRepository = workExperienceRepository;
        this.applicationRepository = applicationRepository;
    }

    public WorkExperience createWorkExperience(Long applicationId, WorkExperience workExperience) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        workExperience.setApplication(application);
        workExperience.setCreatedAt(LocalDateTime.now());
        workExperience.setUpdatedAt(LocalDateTime.now());
        return workExperienceRepository.save(workExperience);
    }

    public List<WorkExperience> getWorkExperienceByApplicationId(Long applicationId) {
        return workExperienceRepository.findByApplicationId(applicationId);
    }

    public Optional<WorkExperience> getWorkExperienceById(Long id) {
        return workExperienceRepository.findById(id);
    }

    public WorkExperience updateWorkExperience(Long id, WorkExperience updatedWorkExperience) {
        WorkExperience existingWorkExperience = workExperienceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("WorkExperience not found"));

        existingWorkExperience.setStartDate(updatedWorkExperience.getStartDate());
        existingWorkExperience.setEndDate(updatedWorkExperience.getEndDate());
        existingWorkExperience.setWorkUnit(updatedWorkExperience.getWorkUnit());
        existingWorkExperience.setDepartment(updatedWorkExperience.getDepartment());
        existingWorkExperience.setPosition(updatedWorkExperience.getPosition());
        existingWorkExperience.setMainTechnicalWork(updatedWorkExperience.getMainTechnicalWork());
        existingWorkExperience.setRemarks(updatedWorkExperience.getRemarks());
        existingWorkExperience.setUpdatedAt(LocalDateTime.now());

        return workExperienceRepository.save(existingWorkExperience);
    }

    public void deleteWorkExperience(Long id) {
        workExperienceRepository.deleteById(id);
    }
}

